package com.fz.us.oa.web.controller.com;

import com.fz.us.admin.base.bean.BaseEnumManager;
import com.fz.us.admin.base.bean.jqgrid.JqGridFilter;
import com.fz.us.admin.base.bean.jqgrid.JqGridPager;
import com.fz.us.admin.base.bean.search.SearchEnum;
import com.fz.us.admin.base.bean.search.order.Order;
import com.fz.us.admin.base.bean.search.page.PageHelp;
import com.fz.us.admin.base.bean.search.result.SearchResultPaging;
import com.fz.us.admin.base.bean.search.rule.Rule;
import com.fz.us.admin.base.utils.DataUtil;
import com.fz.us.admin.base.utils.LogUtil;
import com.fz.us.admin.company.bean.FlowEnum;
import com.fz.us.admin.company.entity.Company;
import com.fz.us.admin.company.entity.Department;
import com.fz.us.admin.company.entity.Duty;
import com.fz.us.admin.company.entity.User;
import com.fz.us.admin.company.service.DepartmentService;
import com.fz.us.admin.company.service.DutyService;
import com.fz.us.admin.company.service.UserService;
import com.fz.us.admin.dict.entity.DictItem;
import com.fz.us.admin.dict.service.DictItemService;

import com.fz.us.oa.core.entity.com.NoticeQuery;
import com.fz.us.oa.core.entity.com.NoticeTest;
import com.fz.us.oa.core.entity.common.FileManage;

import com.fz.us.oa.core.service.com.NoticeQueryService;
import com.fz.us.oa.core.service.com.NoticeTestService;
import com.fz.us.oa.core.service.common.FileManagerService;
import com.fz.us.oa.web.controller.BaseController;
import com.fz.us.oa.web.shiro.bind.annotation.CurrentUser;
import com.fz.us.oa.web.spring.bind.annotation.RequestJsonParam;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.*;

/**
 * 控制器 - 公告通知登记表测试
 * ============================================================================
 * 版权所有 2016 。
 *
 * @version 1.0 2016-12-28 。
 * ============================================================================
 */
@Controller
@RequestMapping(value = "/com/noticeTest")
public class NoticeTestController extends BaseController {


    private static final long serialVersionUID = 4927372640573835145L;
    @Autowired
    private UserService userService;
    @Autowired
    private DictItemService dictItemService;
    @Autowired
    private DepartmentService departmentService;
    @Autowired
    private NoticeTestService noticeTestService;
    @Autowired
    private NoticeQueryService noticeQueryService;
    @Autowired
    private FileManagerService fileManagerService;
    @Autowired
    private DutyService dutyService;

    /**
     * 新建，编辑页面
     */
    @RequestMapping(value = "input", method = RequestMethod.GET, produces = MediaType.TEXT_HTML_VALUE)
    public String input(@CurrentUser User user, Model model,String keyId,String draft,String index,String todo,String remind,String record) {
        ArrayList<DictItem> noticeTypDict = getDictItems(user,"noticeType");
        if (StringUtils.isNotEmpty(keyId)){
            String fileId ="";
            NoticeTest noticeTest = noticeTestService.get(keyId);
            if(noticeTest.getFile() != null && noticeTest.getFile().size()>0){
                for(FileManage f:noticeTest.getFile()){
                    fileId+=f.getId()+",";
                }
            }
            model.addAttribute("keyId", keyId);
            model.addAttribute("fileId", fileId);
            model.addAttribute("noticeTest", noticeTest);
        }
        model.addAttribute("noticeTypDict", noticeTypDict);
        model.addAttribute("draft", draft);
        model.addAttribute("index", index);
        model.addAttribute("todo", todo);
        model.addAttribute("remind", remind);
        model.addAttribute("record", record);
        return "/com/noticeTest_input";
    }



    /**
     * 只读页面
     */
    @RequestMapping(value = "read", method = RequestMethod.GET, produces = MediaType.TEXT_HTML_VALUE)
    public String read(@CurrentUser User user, Model model,String keyId,String draft,String index,String todo,String remind,String record) {
        ArrayList<DictItem> noticeTypDict = getDictItems(user,"noticeType");
        if(StringUtils.isNotEmpty(keyId)) {
            String fileId ="";
            NoticeTest noticeTest = noticeTestService.get(keyId);
            if(noticeTest.getFile() != null && noticeTest.getFile().size()>0){
                for(FileManage f:noticeTest.getFile()){
                    fileId+=f.getId()+",";
                }
            }
            if(StringUtils.equals(noticeTest.getProcessState().name(),"Finished")){
                List<NoticeQuery>  noticeQueryList = noticeQueryService.findUsersByNoticeQuery(user.getId(),keyId);
                if(noticeQueryList.size()==0){
                    NoticeQuery noticeQuery = new NoticeQuery();
                    noticeQuery.setUser(user);
                    noticeQuery.setKeyId(keyId);
                    noticeQueryService.save(noticeQuery);
                }
            }
            LogUtil.info("fileId:"+fileId);
            String isEdit =  isEdit(keyId);
            model.addAttribute("fileId", fileId);
            model.addAttribute("noticeTest", noticeTest);
            model.addAttribute("isEdit", isEdit);
        }

        model.addAttribute("keyId", keyId);
        model.addAttribute("noticeTypDict", noticeTypDict);
        model.addAttribute("draft", draft);
        model.addAttribute("index", index);
        model.addAttribute("todo", todo);
        model.addAttribute("remind", remind);
        model.addAttribute("record", record);
        return "/com/noticeTest_read";
    }

    /**
     * 赋值数据
     */
    private NoticeTest setData(User user, String keyId, String topic, String top, String noticedictId,
                         String departmentId,String object,String hasValid,String validDate,String noticeDepartmentId,
                         String noticeUserId,String fileIds,String content){
        NoticeTest noticeTest = null;
        if(StringUtils.isNotEmpty(keyId)){
            noticeTest = noticeTestService.get(keyId);
        }else{
            noticeTest = new NoticeTest();
            noticeTest.setCreater(user);
        }
        noticeTest.setTopic(topic);
        noticeTest.setTop(top.equals("1") ? true : false);
        noticeTest.setType(dictItemService.get(noticedictId));
        noticeTest.setDepartment(departmentService.get(departmentId));
        noticeTest.setObject(object);
        noticeTest.setHasValid((hasValid != null && hasValid.equals("1")) ? true : false);
        noticeTest.setValidDate(DataUtil.StringToDate(validDate));
        List<Department> departmentList = Lists.newArrayList();
        String dutyIds = "";
        Set<Duty> dutySet = Sets.newHashSet();
        if(StringUtils.isNotEmpty(noticeDepartmentId)){
            String[] idArr = noticeDepartmentId.split(",");
            for(String id:idArr){
                departmentList.add(departmentService.get(id.trim()));
            }
        }
        List<User> userList = Lists.newArrayList();
        if(StringUtils.isNotEmpty(noticeUserId)){
            String[] idArr = noticeUserId.split(",");
            for(String id:idArr){
                userList.add(userService.get(id.trim()));
            }
        }
        List<FileManage> fileManageList = Lists.newArrayList();
        if(StringUtils.isNotEmpty(fileIds)){
            for(String f:fileIds.split(",")){
                fileManageList.add(fileManagerService.get(f.trim()));
            }
        }
        if(StringUtils.equals(object,"1") == true){
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("state", BaseEnumManager.StateEnum.Enable);
            dutySet.addAll(dutyService.getList(map));
        }else if(StringUtils.equals(object,"2") == true){
            for(Department department:departmentList){
                dutySet.addAll(dutyService.getDutys(department));
            }
        }else if(StringUtils.equals(object,"3") == true){
            for(User user1: userList){
                dutySet.addAll(dutyService.getDutys(user1));
            }
        }
        for(Duty duty:dutySet){
            dutyIds += duty.getId()+",";
        }
        if(StringUtils.isNotEmpty(dutyIds)){
            dutyIds = dutyIds.substring(0, dutyIds.length()-1);
        }
        noticeTest.setDutyIds(dutyIds);
        noticeTest.setNoticeDepartment(departmentList);
        noticeTest.setNoticeUser(userList);
        noticeTest.setContent(content);
        noticeTest.setFile(fileManageList);
        noticeTest.setCompany(user.getCompany());
        return noticeTest;
    }

    /**
     * 保存操作
     */
    @RequestMapping(value = "save", method = RequestMethod.POST)
    public Object save(@CurrentUser User user, String keyId, String topic, String top,
                       String noticedictId, String departmentId, String object, String hasValid, String validDate,
                       String noticeDepartmentId, String noticeUsersId, String fileIds, String content) {

        Map<String,Object> rMap=new HashMap<String,Object>();
        NoticeTest noticeTest = setData( user, keyId, topic, top, noticedictId,
                departmentId, object, hasValid, validDate, noticeDepartmentId, noticeUsersId, fileIds, content);
        if(StringUtils.isNotEmpty(keyId)){
            noticeTestService.update(noticeTest);
            rMap.put("message", "更新成功");
        } else {
            noticeTestService.save(noticeTest, "com.fz.us.oa.core.entity.com.NoticeTest");
            rMap.put("message","保存成功");
        }
        rMap.put("state","1");
        rMap.put("keyId", keyId);
        return ajaxJson(rMap);
    }


    // 提交
    @RequestMapping(value = "commit", method = RequestMethod.POST)
    public Object commit(@CurrentUser User user, String keyId, String topic, String top,
                         String noticedictId, String departmentId, String object, String hasValid, String validDate,
                         String noticeDepartmentId, String noticeUsersId, String fileIds, String content, String curDutyId, String comment){

        Map<String,Object> rMap=new HashMap<String,Object>();
        NoticeTest noticeTest = setData( user, keyId, topic, top, noticedictId,
                departmentId, object, hasValid, validDate, noticeDepartmentId, noticeUsersId, fileIds, content);

        if (StringUtils.isNotEmpty(keyId)) {
            noticeTestService.approve(noticeTest, dutyService.get(curDutyId), comment);
        } else {
            noticeTestService.commit(noticeTest,"com.fz.us.oa.core.entity.com.NoticeTest", dutyService.get(curDutyId));
        }
        rMap.put("message","提交成功");
        rMap.put("state","1");
        rMap.put("keyId", keyId);
        return ajaxJson(rMap);
    }

    //审批
    @RequestMapping(value = "approve", method = RequestMethod.POST)
    public Object approve(@CurrentUser User user, String keyId,  String curDutyId, String comment){
        Map<String,Object> rMap=new HashMap<String,Object>();
        NoticeTest noticeTest = noticeTestService.get(keyId);
        noticeTestService.approve( noticeTest, dutyService.get(curDutyId), comment);
        rMap.put("message","提交成功");
        rMap.put("state","1");
        rMap.put("keyId", keyId);
        return ajaxJson(rMap);
    }
    /**
     * 退回
     * @return
     */
    @RequestMapping(value = "back", method = RequestMethod.POST)
    public Object back(@CurrentUser User user, String keyId,String curDutyId, String comment) {
        if (StringUtils.isNotEmpty(keyId)) {
            NoticeTest noticeTest = noticeTestService.get(keyId);
            noticeTestService.back(noticeTest, dutyService.get(curDutyId), comment);
        }
        Map<String,Object> rMap=new HashMap<String,Object>();
        rMap.put("message","退回成功");
        rMap.put("state","1");
        rMap.put("keyId", keyId);
        return ajaxJson(rMap);
    }
    /**
     * 否决
     * @return
     */
    @RequestMapping(value = "deny", method = RequestMethod.POST)
    public Object deny(@CurrentUser User user, String keyId,String curDutyId, String comment) {
        if (StringUtils.isNotEmpty(keyId)) {
            NoticeTest noticeTest = noticeTestService.get(keyId);
            noticeTestService.deny(noticeTest, dutyService.get(curDutyId), comment);
        }
        Map<String,Object> rMap=new HashMap<String,Object>();
        rMap.put("message","否决成功");
        rMap.put("state","1");
        rMap.put("keyId", keyId);
        return ajaxJson(rMap);
    }

    /**
     * 列表
     */
    @RequestMapping(value = "list", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
    @ResponseBody
    public Map<String, Object> list(@CurrentUser User user,Model model,
                                     String viewtype,
                                    JqGridPager pager,
                                    @RequestJsonParam(value = "filters", required = false) JqGridFilter filters) {
        Company company = user.getCompany();
        // 排序
        Order order = null;
        if(viewtype !=null && viewtype.equals("2")){
            order = Order.order("modifyTime", SearchEnum.OrderType.desc);
        }
        /*
        if (StringUtils.isNotBlank(pager.getSidx()) && StringUtils.isNotBlank(pager.getSord())) {
            order = Order.order(pager.getSidx(), SearchEnum.OrderType.valueOf(pager.getSord()));
        }*/
        SearchResultPaging searchResult = null;
       // List<Rule> rules = getSearchFilterRules(pager.getSearch(), filters);
        Map<String,Object> params = new HashMap<String,Object>();
        params.put("company", company);
        params.put("state", BaseEnumManager.StateEnum.Enable);
        if(StringUtils.isNotEmpty(viewtype)) {
            if (viewtype.equals("1")) {
                params.put("invalid", false);
                searchResult = noticeTestService.paging(null,null,order,
                        "com.fz.us.oa.core.entity.com.NoticeTest", new FlowEnum.ProcessState []{FlowEnum.ProcessState.Running, FlowEnum.ProcessState.Backed},params);
            }else if(viewtype.equals("2")){
                //已归档
                searchResult = noticeTestService.paging(null,null,order,
                        "com.fz.us.oa.core.entity.com.NoticeTest", new FlowEnum.ProcessState []{FlowEnum.ProcessState.Finished},params);
            }else if(viewtype.equals("3")){
                //已失效
                params.put("invalid", true);
                searchResult = noticeTestService.paging(null,null,order,
                        "com.fz.us.oa.core.entity.com.NoticeTest", new FlowEnum.ProcessState []{FlowEnum.ProcessState.Running, FlowEnum.ProcessState.Backed,FlowEnum.ProcessState.Finished}, params);
            }
        }else{
            //所有单子
            searchResult = noticeTestService.paging(null,null,order,
                    "com.fz.us.oa.core.entity.com.NoticeTest",
                    new FlowEnum.ProcessState []{FlowEnum.ProcessState.Running, FlowEnum.ProcessState.Backed, FlowEnum.ProcessState.Finished, FlowEnum.ProcessState.Deny}, params);
        }

        List<NoticeTest> noticeTestList = searchResult.getList();
        ArrayList<Map<String, Object>> dataRows = new ArrayList<Map<String, Object>>();
        Map<String, Object> data = new HashMap<String, Object>();
        Map<String,Object> rMap;
        if(viewtype !=null && viewtype.equals("2")){
            for(NoticeTest noticeTest: noticeTestList ){
                if(noticeTest.isTop()){
                    rMap = new HashMap<String, Object>();
                    rMap.put("id",noticeTest.getId());
                    rMap.put("type",noticeTest.getType() != null?noticeTest.getType().getName():"");
                    rMap.put("topic",noticeTest.getTopic());
                    rMap.put("creater", noticeTest.getCreater() != null ? noticeTest.getCreater().getName() : "");
                    rMap.put("createTime", DataUtil.DateToString(noticeTest.getCreateTime(),"yyyy-MM-dd"));
                    rMap.put("modifyTime", DataUtil.DateToString(noticeTest.getModifyTime(),"yyyy-MM-dd"));
                    rMap.put("state",noticeTest.getProcessState().value());
                    dataRows.add( rMap);
                }
            }
            for(NoticeTest noticeTest: noticeTestList){
                if(!noticeTest.isTop()){
                    rMap = new HashMap<String, Object>();
                    rMap.put("id",noticeTest.getId());
                    rMap.put("type",noticeTest.getType() != null?noticeTest.getType().getName():"");
                    rMap.put("topic",noticeTest.getTopic());
                    rMap.put("creater", noticeTest.getCreater() != null ? noticeTest.getCreater().getName() : "");
                    rMap.put("createTime", DataUtil.DateToString(noticeTest.getCreateTime(),"yyyy-MM-dd"));
                    rMap.put("modifyTime", DataUtil.DateToString(noticeTest.getModifyTime(),"yyyy-MM-dd"));
                    rMap.put("state",noticeTest.getProcessState().value());
                    dataRows.add( rMap);
                }
            }
        }else{
            for(NoticeTest noticeTest: noticeTestList){
                    rMap = new HashMap<String, Object>();
                    rMap.put("id",noticeTest.getId());
                    rMap.put("type",noticeTest.getType() != null?noticeTest.getType().getName():"");
                    rMap.put("topic",noticeTest.getTopic());
                    rMap.put("creater", noticeTest.getCreater() != null ? noticeTest.getCreater().getName() : "");
                    rMap.put("createTime", DataUtil.DateToString(noticeTest.getCreateTime(),"yyyy-MM-dd"));
                    rMap.put("modifyTime", DataUtil.DateToString(noticeTest.getModifyTime(),"yyyy-MM-dd"));
                    rMap.put("state",noticeTest.getProcessState().value());
                    dataRows.add(rMap);
            }
        }
        data.put("dataRows", dataRows);
        data.put("page", searchResult.getPageNumber());
        data.put("rows", searchResult.getPageSize());
        data.put("records", searchResult.getTotalCount());
        data.put("total", searchResult.getPageCount());
        return data;
    }

    /**
     * 获取新建人部门
     * @return
     */
    @RequestMapping(value = "getDefaultDept", method = RequestMethod.GET, produces = MediaType.TEXT_HTML_VALUE)
    public Object getDefaultDept(String curDutyId){
        Map<String, Object> data = new HashMap<String, Object>();
        Duty duty = dutyService.get(curDutyId);
        data.put("department",duty.getPower().getDepartment().getName());
        data.put("departmentId",duty.getPower().getDepartment().getId());
        return  ajaxJson(data);
    }

}
